import Vue from 'vue'

const state = {
  loginTimeout: false,    //  登录超时节流用

  wxID: 7,
  scopeId: '',    //  运营范围id
  storeId: '',    //  区域公司id
  storeName: '',    //  区域公司name
  openId: '',     //  用户openId
  unionId: '',    // 用户的unionId
  userInfo: null, //  用户信息
  location: null, //  定位信息  {latitude, longitude}
  locationDetailInfo: null,   //  详细定位信息  {latitude, longitude, name, address}
  addrName: '', //省级名字
  nearestChain: {},   //  最近的门店-首页显示用
  shareUrl: '',   //  分享的webview链接
  sharePageUrl: '', //  分享的小程序页面
  encryptedData: '',
  iv: '',
  indexOptions: {}, //  进入首页时的传参

  cardDepartId: '', //  跳转健康社区用到的区域编码
  showIndexPopup: 0,
  userPhone: '', //  用户手机号
  locationCopy: '',
}

const mutations = {
  updateAppSetting(state, payload) {
    for (let key in payload.settings) {
      Vue.set(state, ['' + key], payload.settings['' + key])
    }
  },
}

const actions = {
  updateAppSetting: ({ state, commit, rootState }, settings) => {
    commit({
      type: 'updateAppSetting',
      settings: settings
    })
  },
  login: ({ state, commit, rootState, dispatch }, isRelogin) => {
    dispatch('updateAppSetting', {
      loginTimeout: false
    })

    return new Promise(async (resolve, reject) => {
      try {
        let code = await dispatch('getLoginCode')
        // await dispatch('getEncData')
        await dispatch('getUserInfo', code)
        console.log(isRelogin)
        if (isRelogin) {
          wx.showToast({
            icon: 'none',
            title: '登录成功，请继续操作',
            duration: 1500,
          })

          setTimeout(() => {
            Vue.prototype.$bus.emit('re-login-success')
          }, 1500)
        }

        resolve()

      } catch (err) {
        wx.showModal({
          title: '提示',
          content: err.msg,
          confirmText: '重试',
          success: (res) => {
            if (res.confirm) {
              dispatch('login', isRelogin)
            }
          }
        })
        reject(err)
      } finally {
        dispatch('updateAppSetting', {
          loginTimeout: false
        })
      }

    })
  },
  //  获取小程序登录code
  getLoginCode: ({ state, commit, rootState }, settings) => {
    console.log('获取小程序code')
    wx.showLoading({
      title: '登录中'
    })

    return new Promise((resolve, reject) => {
      wx.login({
        success: (res) => {
          if (res.code) {
            console.log('code 获取成功')
            wx.hideLoading()
            resolve(res.code)
          } else {
            console.log('登录失败！(01)', res)
            wx.hideLoading()
            reject({
              msg: '登录失败！(01)'
            })
          }
        },
        fail: (err) => {
          console.log('登录失败！(02)', err)
          wx.hideLoading()
          reject({
            msg: '登录失败！(02)'
          })
        }
      })
    })
  },
  //   getEncData:({state, commit, rootState}, settings)=>{

  //     // return new Promise((resolve, reject) => {
  // 　　　　wx.getUserInfo({
  //           withCredentials: true,
  // 　　　　　　success: function(res){
  //               if(res.errMsg == "getUserInfo:ok"){
  //                 console.log('登录成功')
  //                 console.log(res,11)
  //                 wx.hideLoading()
  //     　　　　　　　　commit({
  //                     type: 'updateAppSetting',
  //                     settings: {
  //                       encryptedData:res.encryptedData,
  //                       iv:res.iv
  //                     }
  //                   })
  //               }else{
  //                 wx.hideLoading()
  //             // reject({
  //             //   msg: '登录失败！(01)'
  //             // })
  //               }
  // 　　　　　　},
  //           fail: (err) => {
  //             console.log('登录失败！(02)', err)
  //             wx.hideLoading()
  //             // reject({
  //             //   msg: '登录失败！(02)'
  //             // })
  //           }
  // 　　　　})
  //     // })
  // 　　},
  //  根据code换取用户信息
  getUserInfo: ({ state, commit, rootState }, settings) => {
    console.log('获取商城用户信息')
    // wx.showLoading({
    //   title: '登录中'
    // })
    return new Promise((resolve, reject) => {
      Vue.prototype.$api.getUserInfo({
        code: settings,
        scopeId: state.scopeId,
        storeId: state.storeId,
        wxID: state.wxID,
      }).then(data => {
        wx.hideLoading()

        commit({
          type: 'updateAppSetting',
          settings: {
            userInfo: data.userInfo || null,
            openId: data.openId,
            unionId: data.unionId
          }
        })
        resolve()
      }, err => {
        console.log('登录失败！(03)', err)
        wx.hideLoading()
        reject({
          msg: '登录失败！(03)' + (err && err.msg)
        })
      })
    })

  },
  //  获取分享信息
  loadShareUrl: async ({ state, commit, rootState }, settings) => {
    let shareUrl = state.indexOptions.shareUrl || ''
    let sharePageUrl = state.indexOptions.sharePageUrl || ''

    // test
    // let scene = 't%3D1%3Bcode%3D123456'
    let scene = state.indexOptions.scene
    let type = ''
    if (scene) {
      let sceneObj = Vue.prototype.$utils.getObjByStr(scene, ';')
      type = sceneObj.t || ''

      // todo 会员卡入口注释掉
      // if (type == 1) {   //  会员开卡  t=1
      //   let invCode = sceneObj.code || ''    //  邀请码
      //   sharePageUrl = `/pages/card/bindCard?invCode=${invCode}`
      // }
      if (type == 2) {  //  商品分佣  t=2
        let params = {
          userId: sceneObj.uid,
          shareGoodsId: sceneObj.sid
        }

        shareUrl = `getShareUrlByService;${JSON.stringify(params)}`    //  记录分佣的信息 在跳转的时候拿去换取正真的链接
      }
      if (type == 3) { //  品牌馆 t=3
        // let route = ''
        sharePageUrl = `/pages/webview?phone=${sceneObj.phone}&brandId=${sceneObj.brandId}`
      }
      if(type == 4){  //  商品海报  t=4
        // let params = {
        //   productid: sceneObj.sid,
        //   phone = sceneObj.ph
        // }
        sharePageUrl =  `/pages/webview?phone=${sceneObj.ph}&productid=${sceneObj.sid}`
      }
    }

    commit({
      type: 'updateAppSetting',
      settings: {
        shareUrl: shareUrl,
        sharePageUrl: sharePageUrl,
      }
    })
  },
  /**
   * 根据经纬度换取地理位置描述
   * @param longitude
   * @param latitude
   * @param success
   * @param fail
   */
  getAddress: ({ state, commit }, settings) => {
    Vue.prototype.$myAmapFun.getRegeo({
      location: `${settings.longitude},${settings.latitude}`,
      success: function (data) {
        console.log(111, data);

        let info = data && data[0] || {}
        settings.success && settings.success({
          name: info.name,
          address: info.regeocodeData && info.regeocodeData.formatted_address || '',
          latitude: info.latitude,
          longitude: info.longitude,
        })
      },
      fail: function (info) {
        console.log(222, info);
        settings.fail && settings.fail(info)
      }
    })
  },
  /**
   * 用webview打开【壹药网上商城项目】的H5页面
   * @param route: 路径，如：/user/card/CardMinute?id=111
   * @param jumpType: 跳转方式 push、replace
   * @param sendLocation: 是否拼上经纬度
   */
  openRouteByWebview: ({ state, commit }, settings) => {
    let route = settings.route || '/index'

    if (settings.sendLocation) {      //  给每一个链接拼上经纬度
      route = route.indexOf('?') > -1 ? route + '&' : route + '?'
      route += `lat=${state.location && state.location.latitude || ''}&lng=${state.location && state.location.longitude || ''}`
    }
    mpvue[settings.jumpType == 'replace' ? 'redirectTo' : 'navigateTo']({
      url: `/pages/webview?route=${encodeURIComponent(route)}`
    })
  },

   /**
   * 用webview打开【壹药网上商城商品详情】的H5页面
   * @param route: 路径，如：/user/card/CardMinute?id=111
   * @param jumpType: 跳转方式 push、replace
   * @param sendLocation: 是否拼上商品id
   */
  openGoodsDetailByWebview: ({ state, commit }, settings) => {
    let route = settings.route || '/index'

    if (settings.sendLocation) {      //  给每一个链接拼上商品id
      route = route.indexOf('?') > -1 ? route + '&' : route + '?'
      route +=  `chainId=0&id=${state.productid}`
    }
    mpvue[settings.jumpType == 'replace' ? 'redirectTo' : 'navigateTo']({
      url: `/pages/webview?route=${encodeURIComponent(route)}`
    })
  },

  /**
   * 用webview打开【品牌馆】的H5页面
   * @param route: 路径，如：/user/card/CardMinute?id=111
   * @param jumpType: 跳转方式 push、replace
   * @param sendInfo: 是否拼上品牌馆id，分享人手机号
   */
  openBrandByWebview: ({ state, commit }, settings) => {
    let route = settings.route

    if (settings.sendLocation) {      //  品牌馆id，分享人手机号
      route = route.indexOf('?') > -1 ? route + '&' : route + '?'
      route += `phone=${state.phone}&brandId=${state.brandId}`
    }
    mpvue[settings.jumpType == 'replace' ? 'redirectTo' : 'navigateTo']({
      url: `/pages/webview?route=${encodeURIComponent(route)}`
    })
  },

  /**
   * 用webview打开【直播活动】的H5页面
   * @param route: 路径，如：/user/card/CardMinute?id=111
   * @param jumpType: 跳转方式 push、replace
   * @param : 是否拼上个人信息
   */
  openLiveByWebview: ({ state, commit }, settings) => {
    let route = settings.route || '/detail'

    if (settings.sendUserInfo) {      //  给每一个链接上个人信息
      route = route.indexOf('?') > -1 ? route + '&' : route + '?'
      route += `userInfo=${state.userInfo && JSON.stringify(state.userInfo) || ''}`
    }

    mpvue[settings.jumpType == 'replace' ? 'redirectTo' : 'navigateTo']({
      url: `/pages/webview?type=live&route=${encodeURIComponent(route)}`
    })
  },
  /**
   * 用webview打开【健康社区】的H5页面
   * @param route: 路径，如：/user/card/CardMinute?id=111
   * @param jumpType: 跳转方式 push、replace
   */
  openHealthRouteByWebview: ({ state, commit }, settings) => {
    settings.route = settings.route.indexOf('?') > -1 ? settings.route + '&' : settings.route + '?'
    settings.route += `sourceType=wdxcx&mobile=${state.userInfo.phone}&company=${state.cardDepartId}&unionId=${state.unionId}`
    // settings.route += `sourceType=wdxcx&mobile=${state.userInfo.phone}&company=${state.cardDepartId}`

    mpvue[settings.jumpType == 'replace' ? 'redirectTo' : 'navigateTo']({
      url: `/pages/webview?type=healthWX&route=${encodeURIComponent(settings.route)}`
    })
  }
}

export default {
  state,
  mutations,
  actions
}
